<script setup lang="ts">
  import { defineProps, ref, watch, reactive, computed, onMounted } from 'vue';
  import { useBooleanStore } from '@/store';
  import { TableRowSelection, Notification } from '@arco-design/web-vue';
  import {
    searchByPage,
    getActionContent,
    saveRemark,
  } from '@/api/material-receipt';

  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'id',
      slotName: 'id',
      width: 90,
      ellipsis: true,
      tooltip: true,
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      align: 'center',
      // fixed: 'left',
    },
    {
      title: '成品合格证',
      dataIndex: 'mesCheckQualiticationId',
      width: 200,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '成品型号',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'mProductNumber',
    },

    {
      title: '成品件号',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'qualityCode',
    },
    {
      title: '成品图号',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'itemCode',
    },
    {
      title: '物料名称',
      width: 150,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'itemName',
    },
    {
      title: '数量',
      width: 100,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'deliveryQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '需求单位',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'requireShop',
    },
    {
      title: '协调单状态',
      width: 130,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'isCoor',
    },
    {
      title: '版本号',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'version',
    },
    {
      title: '工艺状态号',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'processStatusNo',
    },
    {
      title: '限用架次',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'substituteCode',
    },
    {
      title: '是否带证',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'isPaper',
    },
    {
      title: '最长保管期',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'maxStorageDate',
    },

    {
      title: '机型',
      width: 100,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'productCode',
    },

    {
      title: '批次',
      width: 100,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'batchNo',
    },
    {
      title: '起始架次',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'startLotNo',
    },

    {
      title: '截止架次',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'endLotNo',
    },
    {
      width: 120,
      title: '接收备注',
      ellipsis: true,
      tooltip: true,
      dataIndex: 'receiveRemark',
    },
    {
      title: 'ERP备注',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'Remark',
    },

    {
      title: '计量单位',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'mdsUnit',
    },

    {
      title: '保质期',
      width: 180,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'ensureDate',
    },
    {
      title: '油封期',
      width: 180,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'sealDate',
    },

    {
      title: '最长保管期',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'maxStorageDate',
    },
    {
      title: '复试日期',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'retestDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交人工号',
      width: 140,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'deliveryEmpCode',
    },

    {
      title: '移交时间',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'deliveryDate',
    },
  ];
  const columnsTwo: any[] = [
    {
      title: '序号',
      dataIndex: 'id',
      slotName: 'id',
      align: 'center',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 100,
      fixed: 'left',
    },
    {
      title: '成品合格证',
      dataIndex: 'mesCheckQualiticationId',
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '成品型号',
      dataIndex: 'mProductNumber',
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '成品件号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '物料编码',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '移交时间',
      dataIndex: 'deliveryDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 200,
    },
    {
      title: '数量',
      dataIndex: 'deliveryQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 100,
    },
    {
      title: '需求单位',
      dataIndex: 'requireShop',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '版本号',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'version',
    },
    {
      title: '工艺状态号',
      width: 120,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'processStatusNo',
    },
    {
      title: '限用架次',
      dataIndex: 'substituteCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '最长保管期',
      dataIndex: 'maxStorageDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '机型',
      dataIndex: 'productCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '批次',
      dataIndex: 'batchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '起始架次',
      dataIndex: 'startLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '截止架次',
      dataIndex: 'endLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '是否带证',
      dataIndex: 'isPaper',
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '供应商',
      dataIndex: 'srmSupplyId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '拒收原因',
      dataIndex: 'rejectReason',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },

    {
      title: '是否直配',
      dataIndex: 'deliveryStatus',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '接收状态',
      dataIndex: 'deliveryStatus',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '复试日期',
      width: 200,
      ellipsis: true,
      tooltip: true,
      dataIndex: 'retestDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      ellipsis: true,
      tooltip: true,
      width: 140,
    },
    {
      title: '交接单id',
      dataIndex: 'wmsDeliveryPlanId',
      ellipsis: true,
      tooltip: true,
      width: 330,
    },
  ];
  const emit = defineEmits(['localTableData']);
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  // 创建一个响应式的本地副本
  const localTableData = ref<any[]>([]);
  const localTableDataTWo = ref<any[]>([]);
  const visible = ref<boolean>(false);
  // 数据库一共有多少条
  const total = ref<number>(0);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(30);
  const pageSizeOptions = ref<number[]>([30, 50, 100, 500]);
  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const selectedKeys = ref<any>([]);
  const selectedTransferKeys = ref<string[]>([]);
  const clickRowColor = ref<string>('');
  // 计算已选择的表格数据
  const selectedTableData = computed(() => {
    return localTableData.value.filter((item: any) =>
      selectedTransferKeys.value?.includes(item.mesCheckQualiticationId)
    );
  });
  const itemCode = ref<string>('');
  const mProductNumber = ref<string>('');
  const qualityCode = ref<string>('');
  const action = ref<string>('');
  // 发送搜索数据
  const flowQueryData = ref({
    searchParams: computed(() => ({
      itemCode: itemCode.value,
      qualityCode: qualityCode.value,
      mProductNumber: mProductNumber.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNum.value,
    })),
    funcType: 'finPro',
  });
  function change(e: any) {
    pageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
  async function recordAction() {
    if (selectedTableData.value?.length === 0) {
      Notification.error({
        title: '错误',
        content: '请选择至少一条数据',
        closable: true,
      });
      return;
    }
    const selectedDataItemCode = computed(() => {
      // 使用 Set 去重
      const uniqueItemCodes = new Set<string>();
      selectedTableData.value.forEach((item: any) => {
        if (item.itemCode) {
          uniqueItemCodes.add(item.itemCode);
        }
      });
      return Array.from(uniqueItemCodes);
    });
    if (selectedDataItemCode.value.length > 1) {
      Notification.error({
        title: '错误',
        content: '存在不相同的图号数据',
        closable: true,
      });
      return;
    }
    const response = await getActionContent({
      itemCode: selectedDataItemCode.value[0],
    });
    if (response.retCode === '200') {
      action.value = response.retMsg ? response.retMsg.pValue : '';
      visible.value = true;
    } else {
      Notification.error({
        title: '错误',
        content: response.message ? response.message : '获取备注失败',
        closable: true,
      });
    }
  }
  async function commitAction() {
    const response = await saveRemark({
      dliverys: selectedTableData.value,
      remark: action.value,
    });
    if (response.retCode === '200') {
      Notification.success({
        title: '成功',
        content: '保存成功',
        closable: true,
      });
    } else {
      Notification.error({
        title: '错误',
        content: response.message ? response.message : '保存失败',
        closable: true,
      });
    }
    selectedTransferKeys.value = [''];
  }
  async function handleSearch() {
    const response = await searchByPage(flowQueryData.value);
    if (response.retCode === '200') {
      localTableData.value = response.responseBody.result;
      total.value = response.responseBody.pageParameter.totalCount;
      pageNum.value = response.responseBody.pageParameter.page;
      pageSize.value = response.responseBody.pageParameter.rows;
      emit('localTableData', localTableData.value);
    }
  }

  const isExpired = (record: any): string => {
    let returnValue = '';
    // 检查 sealDate 是否为有效日期
    if (record.isCoor !== '正常接收') {
      returnValue = 'isCoor-item';
    }
    if (record.sealDate === null || record.sealDate === '') {
      return returnValue; // 如果日期无效，返回未过期
    }

    const currentDate = new Date(); // 获取当前时间的时间戳
    const sealDateObj = new Date(record.sealDate); // 将油封为时间戳
    const diffTime = currentDate.getTime() - sealDateObj.getTime(); // 计算时间差（毫秒）
    const diffDays = diffTime / (1000 * 60 * 60 * 24); // 转换为天数

    if (diffDays > -90 && record.isCoor !== '正常接收') {
      returnValue = 'all-item';
    } else if (diffDays > -90) {
      returnValue = 'expired-item';
    }
    return returnValue;
  };

  const setRowNameTWo = (record: any) => {
    const className = isExpired(record);
    return className;
  };
  // 重置
  function reset() {
    itemCode.value = '';
    qualityCode.value = '';
    mProductNumber.value = '';
    handleSearch();
  }
  onMounted(() => {
    handleSearch();
  });
  // 监听分页
  watch([pageNum, pageSize], () => {
    handleSearch();
  });
  watch(
    () => booleanStore.list,
    () => {
      if (booleanStore.num7 === 5) {
        // 待接收物料
        localTableDataTWo.value = booleanStore.list;
        // 默认全选
        for (let i = 0; i < localTableDataTWo.value[0]?.length; i += 1) {
          if (
            !selectedKeys.value.includes(
              localTableDataTWo.value[0][i].wmsDeliveryPlanId
            )
          )
            selectedKeys.value.push(
              localTableDataTWo.value[0][i].wmsDeliveryPlanId
            );
        }
      }
    }
  );
  watch(
    selectedKeys,
    () => {
      const selectedData = localTableDataTWo.value[0].filter((item: any) =>
        selectedKeys.value.includes(item.wmsDeliveryPlanId)
      );
      const data: any = [];
      selectedData.forEach((item: any) => {
        data.push({
          barcode: item.barcode,
          deliveryQty: item.deliveryQty,
          itemCode: item.itemCode,
          wmsDeliveryPlanId: item.wmsDeliveryPlanId,
        });
      });
      booleanStore.setListTwo(data);
    },
    { deep: true }
  );
  defineExpose({ handleSearch });
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">已移交成品列表</div>
    </template>
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col :span="6">
        <div>
          <a-input
            v-model="itemCode"
            placeholder="成品图号"
            size="large"
            allow-clear
          />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input
            v-model="qualityCode"
            placeholder="成品件号"
            size="large"
            allow-clear
          />
        </div>
      </a-col>
      <a-col :span="6">
        <div>
          <a-input
            v-model="mProductNumber"
            placeholder="成品型号"
            size="large"
            allow-clear
          />
        </div>
      </a-col>
      <a-col :span="6">
        <a-space>
          <a-button type="primary" size="large" @click="handleSearch">
            查询
          </a-button>
          <a-button size="large" @click="reset">重置</a-button>
          <a-button type="primary" size="large" @click="recordAction">
            录入备注信息
          </a-button>
        </a-space>
      </a-col>
      <a-col :span="24" style="margin-top: 8px">
        <a-table
          v-model:selected-keys="selectedTransferKeys"
          :stripe="true"
          class="top-table"
          :pagination="false"
          :columns="columns"
          :sticky-header="true"
          :data="localTableData"
          column-resizable
          :scroll="{ y: 400 }"
          row-key="mesCheckQualiticationId"
          :row-selection="rowSelection"
          style="height: 250px"
          :row-class="setRowNameTWo"
        >
          <template #id="{ record }">{{
            localTableData.indexOf(record) + 1
          }}</template>
        </a-table>
        <div class="page-position">
          <a-pagination
            :total="total"
            :current="pageNum"
            :page-size="pageSize"
            :page-size-options="pageSizeOptions"
            show-total
            show-jumper
            show-page-size
            @change="change"
            @update:page-size="changeSize"
          />
        </div>
      </a-col>
    </a-row>
  </a-card>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font"
        >待接收成品列表(共{{
          localTableDataTWo[0] ? localTableDataTWo[0].length : 0
        }}条)</div
      >
    </template>
    <a-table
      v-model:selectedKeys="selectedKeys"
      :stripe="true"
      style="white-space: nowrap; height: 250px"
      :columns="columnsTwo"
      :data="localTableDataTWo[0]"
      :row-selection="rowSelection"
      row-key="wmsDeliveryPlanId"
      :scroll="{ y: 400 }"
      :pagination="false"
    >
      <template #id="{ record }">{{
        localTableDataTWo[0].indexOf(record) + 1
      }}</template>
    </a-table>
  </a-card>
  <a-modal
    v-model:visible="visible"
    @cancel="() => (visible = !visible)"
    @ok="commitAction"
  >
    <template #title> 备注录入 </template>
    <span>备注:</span>
    <a-input v-model="action" size="large" />
  </a-modal>
</template>

<style scoped>
  .top-table {
    white-space: nowrap;
    margin-top: 8px;
    z-index: 1;
  }
  .page-position {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }

  :deep(.expired-item > .arco-table-td) {
    color: red !important;
  }
  :deep(.isCoor-item > .arco-table-td) {
    background-color: rgb(252, 174, 174) !important;
  }
  :deep(.all-item > .arco-table-td) {
    color: red !important;
    background-color: rgb(252, 174, 174) !important;
  }
  :deep(.isCoor-item > .arco-table-col-fixed-left > .arco-table-td) {
    background-color: rgb(252, 174, 174) !important;
  }
</style>
